<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Admin\Data\Common;
use Admin\Entity\ExpressPushReceive;
use Admin\Service\ExpressPushReceiveManager;
use Doctrine\ORM\EntityManager;
use Laminas\Crypt\BlockCipher;
use Laminas\Json\Json;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Sales\Entity\Order;
use Sales\Entity\OrderGoods;
use Sales\Service\OrderGoodsManager;
use Sales\Service\OrderManager;
use Sales\Service\OrderStatusManager;

class PushReceiveController extends AbstractActionController
{
    private $translator;
    private $entityManager;
    private $expressPushReceiveManager;
    private $orderGoodsManager;
    private $orderManager;
    private $orderStatusManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager,
        ExpressPushReceiveManager $expressPushReceiveManager,
        OrderGoodsManager $orderGoodsManager,
        OrderManager $orderManager,
        OrderStatusManager $orderStatusManager
    )
    {
        $this->translator   = $translator;
        $this->entityManager= $entityManager;
        $this->expressPushReceiveManager = $expressPushReceiveManager;
        $this->orderGoodsManager = $orderGoodsManager;
        $this->orderManager = $orderManager;
        $this->orderStatusManager= $orderStatusManager;
    }

    public function indexAction()
    {
        return $this->response->setContent('没有内容');
    }

    /**
     * 接收配送推送信息
     * @return mixed|JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function expressPushDataAction()
    {
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();

            $serviceConfig = Common::readConfigFile('dbshopService');
            $deliveryConfig= Common::readConfigFile('delivery');
            $deliveryApiType    = $deliveryConfig['deliveryApiType'] ?? '';
            $deliveryApiKey     = $deliveryConfig['deliveryApiKey'] ?? '';

            if (
                $deliveryConfig['deliveryApiState'] != 1
                || $deliveryApiType != 'longExpressPush'
                || empty($deliveryApiKey)
                || !isset($data['dataStr'])
                || empty($data['dataStr'])
                || !$serviceConfig['key']
                || !$serviceConfig['code']
                || !$serviceConfig['userName']
            ) return $this->response->setContent('');

            $blockCipher = BlockCipher::factory('openssl', ['algo' => 'aes', 'mode' => 'gcm']);
            $blockCipher->setKey($serviceConfig['key']);
            $dataArray =  Json::decode($blockCipher->decrypt($data['dataStr']), 1);
            if (
                $dataArray['serviceKey'] != $deliveryApiKey
                || !isset($dataArray['orderSn'])
                || !isset($dataArray['comCode'])
                || !isset($dataArray['comNumber'])
                || !isset($dataArray['expressState'])
                || !isset($dataArray['receiveBody'])
            ) return $this->response->setContent('');

            $orderInfo = $this->entityManager->getRepository(Order::class)->findOneBy(['orderSn' => $dataArray['orderSn']]);
            if ($orderInfo) {
                $expressReceive = $this->entityManager->getRepository(ExpressPushReceive::class)->findOneBy(['orderId' => $orderInfo->getOrderId(), 'comCode' => $dataArray['comCode'], 'comNumber' => $dataArray['comNumber']]);
                if ($expressReceive) {
                    $this->expressPushReceiveManager->editExpressPushReceive(['receiveBody' => $dataArray['receiveBody'], 'updateTime'  => time()], $expressReceive);
                } else {
                    if ($orderInfo->getDeliveryMode() == 2) {
                        $delivery = $this->entityManager->getRepository(OrderGoods::class)->findOneBy(['orderId' => $orderInfo->getOrderId(), 'expressNumber' => $dataArray['comNumber']]);
                    } else {
                        $delivery = $orderInfo->getExpressNumber() == $dataArray['comNumber'];
                    }

                    if ($delivery) {
                        $this->expressPushReceiveManager->addExpressPushReceive([
                            'orderId'   => $orderInfo->getOrderId(),
                            'comCode'   => $dataArray['comCode'],
                            'comNumber' => $dataArray['comNumber'],
                            'receiveBody' => $dataArray['receiveBody'],
                            'updateTime'  => time()
                        ]);
                    }
                }

                //当为单独配送时，且配送状态为已经签收，进行的处理
                if ($orderInfo->getDeliveryMode() == 2 && $dataArray['expressState'] == 3) {
                    $orderOneGoods = $this->entityManager->getRepository(OrderGoods::class)->findOneBy(['orderId' => $orderInfo->getOrderId(), 'expressNumber' => $dataArray['comNumber'], 'goodsStatus' => 50]);
                    if ($orderOneGoods) $this->orderGoodsManager->editOrderGoods(['goodsStatus' => Common::ORDER_GOODS_RECEIVED], $orderOneGoods);
                }

                //开启推送签收确认收货
                if ($deliveryConfig['pushOrderFinish'] == 1 && $dataArray['expressState'] == 3 && $orderInfo->getOrderStatus() >= Common::ORDER_GOODS_SHIPPED && $orderInfo->getOrderStatus() < Common::ORDER_GOODS_RECEIVED) {
                    $receiveState = true;
                    if ($orderInfo->getDeliveryMode() == 2) {
                        $orderGoods = $this->entityManager->getRepository(OrderGoods::class)->findBy(['orderId' => $orderInfo->getOrderId(), 'goodsType' => 1]);
                        if ($orderGoods) foreach ($orderGoods as $orderGoodsValue) {
                            if ($orderGoodsValue->getGoodsStatus() <= 50) {
                                $receiveState = false;
                                break;
                            }
                        }
                    }
                    if ($receiveState) {
                        $orderInfo = $this->orderManager->editOrder(['orderStatus' => Common::ORDER_GOODS_RECEIVED, 'orderFinishTime' => time()], $orderInfo);
                        $this->orderStatusManager->addOrderStatus(['orderStatus' => $orderInfo->getOrderStatus(), 'operateUser' => $this->translator->translate('买家已签收，系统处理'), 'orderId' => $orderInfo->getOrderId(), 'statusInfo' => $this->translator->translate('确认收货'), 'statusTime' => $orderInfo->getOrderFinishTime()]);

                        $this->getEventManager()->trigger('shop.order.receipt.post', $this, ['orderInfo' => $orderInfo]);
                    }
                }

            }
        }

        return new JsonModel([
            'code'      => 200,
            'status'    => 'success',
            'message'   => ''
        ]);
    }
}